package user

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"goAdminV1/api/user/v1"
)

func (c *ControllerV1) User(ctx context.Context, req *v1.UserReq) (res *v1.UserRes, err error) {

	// 初始化响应结构体
	res = &v1.UserRes{}

	// 获取数据库实例
	db := g.DB()

	// 构建查询条件
	query := db.Model("users").Safe()

	if req.Username != "" {
		query = query.Where("username", req.Username)
	}
	if req.Email != "" {
		query = query.Where("email", req.Email)
	}
	if req.Status != 0 {
		query = query.Where("status", req.Status)
	}
	if req.DepartmentId != 0 {
		query = query.Where("department_id", req.DepartmentId)
	}

	// 查询数据总数量
	total, err := query.Count()
	if err != nil {
		return nil, err
	}

	// 检查分页参数
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.Limit <= 0 {
		req.Limit = 10
	}

	// 计算偏移量
	offset := (req.Page - 1) * req.Limit
	g.Dump(offset, total)
	var userInfos []v1.UserInfo // 返回空列表
	// 判断偏移量是否超出数据范围
	err = query.Limit(req.Limit).Offset(offset).Scan(&userInfos)
	if err != nil {
		return nil, err
	}

	// 填充分页响应结构体
	res.Limit = req.Limit
	res.Total = total
	res.Data = userInfos

	return res, nil
}
